<?php
/**
 * Created by jinqiang on 2024/8/26 16:50.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Soa;


use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyPricingExamineTable;
use App\Http\Models\Mysql\SsyPricingOrderTable;
use App\Http\Models\Mysql\VerifyPriceTable;
use App\Http\Repository\ApprovalRepository;
use App\Http\Repository\FeishuRepository;

class PriceOrderService
{
    public function search($param)
    {
        //废弃
        $conn = (new SsyPricingOrderTable());
        if(isset($param['s_status']) && $param['s_status'] != ""){
            $conn = $conn->where('s_status', $param['s_status']);
        }
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', $param['type_no']);
        }
        if($param['valuation_purpose'] ?? ""){
            $conn = $conn->where('valuation_purpose', $param['valuation_purpose']);
        }
        if($param['pricing_number'] ?? ""){
            $conn = $conn->where('pricing_number', 'like', $param['pricing_number'].'%');
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function searchCheck($param)
    {
        $conn = (new SsyPricingExamineTable());
        if(isset($param['status']) && $param['status'] != ""){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('processing_code', 'like', $param['processing_code']."%");
        }
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', 'like', $param['type_no']."%");
        }
        if($param['supplier_id'] ?? ""){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'])->toArray();
        $ids = array_column($res['data'], 'id');
        $runMap = [];
        if(!empty($ids)){
            $runList = (new SsyFeishuApprovalBindingTable())->whereIn('data_id', $ids)->where('types', 20)->get(['data_id', 'instance_code'])->toArray();
            $runMap = array_column($runList, 'instance_code', 'data_id');
        }
        foreach ($res['data'] as &$item){
            $item['images'] = !empty($item['images']) ? unserialize($item['images']) : "";
            $item['images'] = !empty($item['images']) ? array_column($item['images'], "url") : "";
            $item['run_id'] = $runMap[$item['id']] ?? "";
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function setPricingExamine($param)
    {
        $examineObj = (new SsyPricingExamineTable())->where('id', (Int)$param['id'])->first()->toArray();
        //大货核价
        $bigVerifyPirceObj = (new VerifyPriceTable())->where('number', $examineObj['big_pricing_number'])->first()->toArray();
        if(empty($examineObj['process_pricing_price']) || empty($bigVerifyPirceObj)){
            return ['code' => -1, 'msg' => '设置失败：成衣成本加价总价为空, 请锁定大货核价编码并更新后再尝试!'];
        }
        //实付核价
        $payVerifyPricePbj = (new VerifyPriceTable())->where('number', $param['pay_pricing_number'])->first()->toArray();
        //差价
        $differencePrice = $payVerifyPricePbj['f65']-$bigVerifyPirceObj['f65'];// 差价=实付总价-大货总价
        if(!empty($differencePrice) && empty($param['reason'])){
            return ['code' => -1, 'msg' => '设置失败：有差价, 填写调整原因'];
        }
        $images = $param['images'] ?? [];
        $save = [
            'pay_pricing_number' => $payVerifyPricePbj['number'],//实付核价编码
            'pay_process_price' => $payVerifyPricePbj['f65'],//成衣成本加价总价--实付
            'pay_pricing_price' => $payVerifyPricePbj['f67'],//成本加价总价--实付
            'difference_price' => $differencePrice,
            'reason' => $param['reason'],
            'remarks' => $payVerifyPricePbj['comment'],
            'images' => count($images) ? serialize($images) : "",
            'big_pricing_price' => $bigVerifyPirceObj['f67'],//成本加价总价--大货
            'process_pricing_price' => $bigVerifyPirceObj['f65']//成衣成本加价总价--大货
        ];
        return (new SsyPricingExamineTable())->updateData((Int)$param['id'], $save);
    }

    public function approvalProcess($param)
    {
        //获取审批数据
        $examineObj = (new SsyPricingExamineTable())->where('id', (Int)$param['id'])->first()->toArray();
        if(!empty($examineObj['images'])){
            $examineObj['images'] = unserialize($examineObj['images']);
        }
        $examineObj['base_list'] = [
            ['processing_code' => $examineObj['processing_code'], 'type_no' => $examineObj['type_no']]
        ];
        $examineObj['pricing_number_list'] = [
            ['big_pricing_number' => $examineObj['big_pricing_number'], 'pay_pricing_number' => $examineObj['pay_pricing_number']]
        ];
        $examineObj['difference_price_list'] = [
            [
                'big_pricing_price' => $examineObj['big_pricing_price'],
                'pay_pricing_price' => $examineObj['pay_pricing_price'],
                'difference_price' => $examineObj['difference_price']
            ]
        ];
        //获取审批流程
        $subjects = [];
        foreach (config("scm.subject") as $item) {
            if(isset($subjects[$item['brand_code_s']])){
                continue;
            }
            $subjects[$item['brand_code_s']] = [
                'hjd_approval_code' => $item['hjd_approval_code'],
                'is_subject' => $item['is_subject']
            ];
        }
        $brandCode = substr($examineObj['type_no'], 0, 1);
        $isSubject = $subjects[$brandCode]['is_subject'];
        $flow = (new FeishuRepository($isSubject))->getFlow($param['run_id']);
        return ['flow' => $flow, 'data' => $examineObj];
    }

    public function submit($id)
    {
        $examineObj = (new SsyPricingExamineTable())->where('id', $id)->first()->toArray();
        if(empty($examineObj['big_pricing_number']) || empty($examineObj['big_pricing_price']) || empty($examineObj['pay_pricing_number']) ||
            empty($examineObj['pay_pricing_price']) || empty($examineObj['factory_contract_no'])){
            return ['code' => -1, 'msg' => '请确认大货核价、实付核价、工厂合同号是否正确!'];
        }
        //获取审核通过的首单实付
        $examineFirstObj = (new SsyPricingExamineTable())->where('type_no', $examineObj['type_no'])->where('status', 2)->orderBy('examinetime', 'asc')->first();
        $save = [
            'status' => 1,
            'addtime' =>date("Y-m-d H:i:s"),
            'pay_float_type' => 1,
            'pay_float' => 0,
            'pay_float_lv' => 0
        ];
        if(!empty($examineFirstObj)){
            if($examineObj['pay_process_price'] >= $examineFirstObj->pay_process_price){
                $save = array_merge($save, [
                    'pay_float_type' => 0,
                    'pay_float' => $float =round($examineObj['pay_process_price']-$examineFirstObj->pay_process_price, 2),
                    'pay_float_lv' => round($float/$examineFirstObj->pay_process_price, 4)
                ]);
            }else{
                $save = array_merge($save, [
                    'pay_float_type' => 1,
                    'pay_float' => $float = round($examineFirstObj->pay_process_price-$examineObj['pay_process_price'], 2),
                    'pay_float_lv' => round($float/$examineFirstObj['pay_process_price'], 4)
                ]);
            }
        }
        $user = auth()->guard("api")->user()->toArray();
        //没有差价,自动审批通过
        if($examineObj['difference_price'] == 0){
            $save = array_merge($save, ['status' => 2, 'examinetime' => date("Y-m-d H:i:s")]);//自动审批通过
            //创建无差价审批流程
            //$res = ApprovalRepository::addFlowPricing($examineObj, $user);
            //更新回货统计表 实付价
            $res = ApprovalRepository::setReturnsPrice($examineObj, 2);
        }else{
            //发起飞书审批
            $subjectMap = array_column(config("scm.subject"), null, 'brand_code_jy');
            $subjects = array_column(config("scm.subject"), null, 'is_subject');
            $jyObj = (new SsyJyProductListTable())->where('product_code', "like", $examineObj['type_no']."%")->first(['brand_code'])->toArray();
            $isSubject = $subjectMap[$jyObj['brand_code']]['is_subject'];
            $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
            $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
            $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
            $fsApprovalCode = $subjects[$approvalSubject]['hjd_approval_code'];
            //$fsApprovalCode = "3CCBF95A-F510-4311-A534-F6E5097B4A19";//内部测试
            if(empty($fsApprovalCode)){
                return ['code' => -1, 'msg' => '当前主体未添加该审批流程'];
            }
            //基本信息
            $infoStr = '[{"id": "processing_code","type":"input","value":"' .$examineObj['processing_code'].'"},{"id": "type_no","type":"input","value":"'
                .$examineObj['type_no'].'"}]';
            //核价编码
            $pricingNumberStr = '[{"id": "big_pricing_number","type":"input","value":"'
                .$examineObj['big_pricing_number'].'"},{"id": "pay_pricing_number","type":"input","value":"' .$examineObj['pay_pricing_number'] .'"}]';
            //价格变动
            $pricingChange = '[{"id": "process_pricing_price","type":"input","value":"' .$examineObj['process_pricing_price']
                .'"},{"id": "pay_process_price","type":"input","value":"' .$examineObj['pay_process_price']
                .'"},{"id": "difference_price","type":"input","value":"' .$examineObj['difference_price'] .'"}]';
            //截图说明
            $imageStr = "";
            $images = unserialize($examineObj['images']);
            if(!empty($images) && isset($images[0]['url'])){
                foreach ($images as $item){
                    $upRes = (new FeishuRepository($isSubject))->upload([
                        'name' => "核价变动".$examineObj['processing_code'],
                        'type' => 'image',
                        'content' => $item['url']
                    ]);
                    if($upRes['data']['code'] ?? ""){
                        $imageStr .= ','.'"'.$upRes['data']['code'].'"';
                    }
                }
                $imageStr = ltrim($imageStr,",");
            }
            $subjectLabelMap = ["kz" => "mcms0z7p-e0q5lblelyv-0", "mz" => "mcms0z7p-hh73rao0qg-0", "qyx" => "mcms0z7p-qgfcilj1e-0"];
            //品牌字段
            $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
            $postData = [
                "approval_code" => $fsApprovalCode,
                "user_id" => $fsUserId,
                "open_id" => $fsOpenId,
                "form" => '['.$brandStr.'{"id":"factory_contract_no","type":"input","value":"'.$examineObj['factory_contract_no'].'"},{"id":"factory_name","type":"input","value":"'
                    .$examineObj['factory_name'].'"},{"id": "info","type": "fieldList","value": ['.$infoStr.']},{"id": "pricing_number","type": "fieldList","value": ['.
                    $pricingNumberStr.']},{"id": "pricing_change","type": "fieldList","value": ['.$pricingChange.']},{"id":"reason","type":"textarea","value":"'
                    .$examineObj['reason'].'"},{"id":"image","type":"image","value":[' .$imageStr.']}]'
            ];
            $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
            if($res['code'] != '0'){
                return ['code' => -1, 'msg' => '创建核价单审核,失败!'.($res['msg'] ?? ""), 'data' => $res];
            }
            (new SsyFeishuApprovalBindingTable())->createData([
                "instance_code" => $res['data']['instance_code'],
                "data_id" => $examineObj['id'],
                "types" => 20,
                "createtime" => date('Y-m-d H:i:s')
            ]);
            //$res = ApprovalRepository::addFlow($examineObj, 6);
        }
        if($res['code'] !== 0){
            return $res;
        }
        return (new SsyPricingExamineTable())->updateData($id, $save);
    }
}
